<template>
   <div style="height:100%;">
      <div>
        <div class='content-title'>
          <div class='content-title-child'>热线管理</div>
        </div>
        <hr class='content-hr'/>
      </div>
      <!--数据筛选条件+按钮-->
      <el-row style="margin-top:10px" class='hotlineClass'>
        <el-form v-model="filterForm" ref="filterForm":inline="true">
          <el-form-item label="所属机场：">
            <el-select v-model="filterForm.airportId" clearable placeholder="请选择" @change="changeCategory">
                <el-option
                    v-for="item in airportNameList"
                    :key="item.airportId"
                    :value="item.airportId"
                    :label="item.label">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="float:right;margin-right:20px">
            <el-button type="warning" @click="addVisable = true">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!--表格数据-->
      <el-row>
        <el-table 
          v-loading="loading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          :data="filterFormFro.tableData" 
          :border="true"
          :row-class-name="tableRowClassName"
          :header-cell-class-name = "tableHeaderClassName"
          v-bind:style="{width: tableWidth + 'px'}">
            <el-table-column prop="index" label="序号" sortable min-width="20%">
            </el-table-column>
            <el-table-column prop="hotLineName" label="热线名称" sortable min-width="35%">
            </el-table-column>
            <el-table-column prop="hotLineNum" label="热线号码" min-width="35%">
            </el-table-column>
            <el-table-column prop="sortNum" label="排序编号" min-width="10%">
            </el-table-column>
            <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!--表格下方分页-->
      <el-row>
        <div class="pagination" style="text-align:center" v-show="paginationVisible">
          <el-pagination
            @current-change="handleCurrentChange"
            background
            :page-size="15"
            :current-page="filterForm.pageNum"
            layout="total, prev, pager, next"
            :page-count="filterFormFro.allPages">
          </el-pagination>
        </div>
      </el-row>
      <!-- 添加热线信息弹窗 -->
      <el-dialog title="增加热线:"  :visible.sync="addVisable"
          :closeOnClickModal="false"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          width="550px"
          class="categoryManaDialog"
          @close="resetForm('addForm')">
        <el-form :model='addForm' ref="addForm" :rules="addRules">
            <el-form-item label="热线名称：" :label-width="formLabelWidth" prop="hotLineName">
              <el-input style='width:240px' @keyup.native="addForm.hotLineName=addForm.hotLineName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable v-model.trim="addForm.hotLineName"></el-input>
            </el-form-item>
            <el-form-item label="热线号码：" :label-width="formLabelWidth" prop="hotLineNum">
              <el-input style='width:240px' type="number"  clearable  v-model="addForm.hotLineNum"></el-input>
            </el-form-item>
            <el-form-item label="所属机场：" :label-width="formLabelWidth" prop="airportId">
              <el-select style="width:240px" v-model="addForm.airportId" clearable placeholder="请选择">
                <el-option
                    v-for="item in airportNameList"
                    :key="item.airportId"
                    :value="item.airportId"
                    :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="sortNum">
              <el-input style='width:240px' type="number" v-model="addForm.sortNum"></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button style="width:240px" type="primary" @click="submitAdd()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 编辑热线信息弹窗 -->
      <el-dialog title="编辑热线信息:"   :visible.sync="editVisable"
          :closeOnClickModal="false" 
          width="550px"
          class="categoryManaDialog"
          :close-on-click-modal="false" 
          :close-on-press-escape="false"
          @close="resetForm('editForm')">
        <el-form :model='editForm' ref="editForm" :rules="editRules">
            <el-form-item label="热线名称：" :label-width="formLabelWidth" prop="hotLineName">
              <el-input style='width:80%' @keyup.native="editForm.hotLineName=editForm.hotLineName.replace(/[^\w\u4e00-\u9fa5\s]/g, '')" clearable v-model.trim="editForm.hotLineName"></el-input>
            </el-form-item>
            <el-form-item label="热线号码：" :label-width="formLabelWidth" prop="hotLineNum">
              <el-input style='width:80%' type="number"  clearable v-model="editForm.hotLineNum" ></el-input>
            </el-form-item>
            <el-form-item label="所属机场：" :label-width="formLabelWidth" prop="airportId">
              <el-select v-model="editForm.airportId" clearable placeholder="请选择" style='width:80%'>
                  <el-option
                      v-for="item in airportNameList"
                      :key="item.airportId"
                      :value="item.airportId"
                      :label="item.label">
                  </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序编号：" :label-width="formLabelWidth" prop="sortNum">
              <el-input style='width:80%' clearable v-model="editForm.sortNum"  type="number"></el-input>
            </el-form-item>
            <el-form-item label="" :label-width="formLabelWidth" >
              <el-button style="width:240px" type="primary" @click="submitEdit()">保 存</el-button>
            </el-form-item>
        </el-form>
      </el-dialog>
    </div>
</template>
<script>
import apiBus from '../../api/businessPlat/apiBus.js'
import '../../../static/css/businessPlat/common.css'
import '../../../static/css/businessPlat/hotline.css'
export default {
  created () {
    this.getAllAirportFor()
    this.getHotLintFor()
  },
  data () {
    var checkNumber = (rule, value, callback) => { // 热线排序编号验证
      if (value > 99) {
        callback(new Error('热线排序编号最大为99'))
      } else {
        callback()
      }
    }
    var checkInetger = (rule, value, callback) => { // 整数验证
      if (value % 1 === 0 && value > 0) {
        callback()
      } else {
        callback(new Error('请输入正整数'))
      }
    }
    return {
      airportNameList: [],
      filterForm: { // 筛选表单
        airportId: '',
        pageNum: 1,
        pageSize: 20
      },
      filterFormFro: {
        tableData: [],
        allPages: 1
      },
      tableWidth: '', // 表格宽度
      loadingText: '正在拼命加载中，请稍等......',
      loading: true,
      paginationVisible: false, // 表格下方的分页显示
      noteVisible: false,
      formLabelWidth: '170px',
      addForm: { // 增加热线表单
        sortNum: '',
        hotLineName: '',
        airportId: '',
        hotLineNum: ''
      },
      addVisable: false,
      editVisable: false,
      editForm: { // 编辑热线表单
        sortNum: 0,
        hotLineName: '',
        airportId: '',
        hotLineNum: 0
      },
      deleteForm: {
        hotLineName: '',
        hotLineNum: '',
        sortNum: ''
      },
      addRules: {
        hotLineName: [
          { required: true, message: '请填写热线名称', trigger: 'blur' },
          { max: 8, message: '热线名称最多8个字', trigger: 'blur' }
        ],
        hotLineNum: [
          { required: true, message: '请填写热线号码', trigger: 'blur' },
          { max: 12, message: '热线号码最多12个数字', trigger: 'blur' },
          { min: 3, message: '热线号码最少3个数字', trigger: 'blur' }
        ],
        airportId: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        sortNum: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      },
      editRules: {
        hotLineName: [
          { required: true, message: '请填写热线名称', trigger: 'blur' },
          { max: 8, message: '热线名称最多8个字', trigger: 'blur' }
        ],
        hotLineNum: [
          { required: true, message: '请填写热线号码', trigger: 'blur' },
          { max: 12, message: '热线号码最多12个数字', trigger: 'blur' },
          { min: 3, message: '热线号码最少3个数字', trigger: 'blur' }
        ],
        airportId: [
          { required: true, message: '请选择机场', trigger: 'change' }
        ],
        sortNum: [
          { required: true, message: '请填写排序编号', trigger: 'blur' },
          { validator: checkInetger, trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 分页页面跳转时
    handleCurrentChange (val) {
      this.filterForm.pageNum = val
      this.getHotLintFor()
    },
    // 更换下拉框飞机场
    changeCategory (value) {
      this.filterForm.pageNum = 1
      this.getHotLintFor()
      this.airportNameList.forEach((item) => {
        if (item.airportId === value) {
          this.$message.success('分类选择：' + item.airportName)
          return
        }
      })
    },
    tableHeaderClassName ({row, column, rowIndex, columnIndex}) {
      if (rowIndex === 0) {
        return 'headerClass'
      }
    },
    tableRowClassName ({row, rowIndex}) {
      return 'rowClass'
    },
    // 点击表格中的“编辑”按钮
    handleEdit (index, row) {
      this.editVisable = true
      let data = this.filterFormFro.tableData[index]
      this.editForm.hotLineName = data.hotLineName.trim()
      this.editForm.hotLineNum = data.hotLineNum.trim()
      this.editForm.sortNum = data.sortNum
      this.editForm.airportId = data.airportId
      this.editForm.hotLineId = data.hotLineId
    },
    // 点击表格中的“删除”按钮
    handleDelete (index, row) {
      let data = this.filterFormFro.tableData[index]
      this.deleteForm.hotLineId = data.hotLineId
      this.$confirm('确定删除该热线信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteHotLintFor()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    cancleEdit (formName) {
      this.resetError(formName)
      this.editVisable = false
    },
    // 重置表单
    resetError (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    setDeleteFro () {
      this.noteVisible = false
      this.$message.success('热线<' + this.deleteForm.hotLineName + '>已删除')
    },
    // 重置表单
    resetForm (formName) {
      this.$nextTick(function () {
        this.$refs[formName].resetFields()
      })
    },
    // 增加热线，点击“保存”
    submitAdd () {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.addHotLintFor()
        } else {
          return false
        }
      })
    },
    // 编辑热线信息，点击“保存”
    submitEdit () {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.editHotLintFor()
        } else {
          return false
        }
      })
    },
    /** ***************************** 向后台发送请求 ***************************************** */
    // 向后台请求热线列表
    getHotLintFor () {
      this.loading = true
      this.paginationVisible = false
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({
          pageNum: parseInt(this.filterForm.pageNum),
          pageSize: 15,
          airportId: parseInt(this.filterForm.airportId)
        })
      }
      this.filterFormFro.tableData = []
      apiBus.getHotLint(para).then(res => {
        this.loading = false
        if (res.data.body.result === 1000) {
          this.filterFormFro.tableData = res.data.body.content.list
          if (res.data.body.content.list.length > 0) {
            let resData = res.data.body.content.list
            for (let i = 0; i < resData.length; i++) {
              this.filterFormFro.tableData[i].index = (parseInt(this.filterForm.pageNum) - 1) * 15 + i + 1
            }
            this.filterFormFro.allPages = res.data.body.content.allPages
            this.filterFormFro.allPages > 1 ? this.paginationVisible = true : this.paginationVisible = false
            this.$message.success('成功提取热线信息！')
          } else {
            this.$message.warning('没有任何热线信息')
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.loading = false
        this.$message.error(error)
      })
    },
    // 向后台发送增加热线信息
    addHotLintFor () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'hotLineService_v1'
        }),
        body: JSON.stringify({
          hotLineName: this.addForm.hotLineName,
          airportId: parseInt(this.addForm.airportId),
          hotLineNum: this.addForm.hotLineNum,
          sortNum: this.addForm.sortNum
        })
      }
      apiBus.addHotLint(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterForm.pageNum = 1
          this.getHotLintFor()
          this.$message.success('成功添加热线信息！')
          this.addVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台发送增加热线信息
    editHotLintFor () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'hotLineService_v1'
        }),
        body: JSON.stringify({
          hotLineId: parseInt(this.editForm.hotLineId),
          hotLineName: this.editForm.hotLineName.trim(),
          airportId: parseInt(this.editForm.airportId),
          hotLineNum: this.editForm.hotLineNum.trim(),
          sortNum: this.editForm.sortNum
        })
      }
      apiBus.editHotLint(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterForm.pageNum = 1
          this.getHotLintFor()
          this.$message.success('成功编辑热线信息！')
          this.editVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 向后台发送删除热线信息
    deleteHotLintFor () {
      let para = {
        header: JSON.stringify({
          token: sessionStorage.getItem('token'),
          beanId: 'hotLineService_v1'
        }),
        body: JSON.stringify({
          hotLineId: parseInt(this.deleteForm.hotLineId)
        })
      }
      apiBus.deleteHotLint(para).then(res => {
        if (res.data.body.result === 1000) {
          this.filterForm.pageNum = 1
          this.getHotLintFor()
          this.$message.success('成功删除该热线信息！')
          this.deleteVisable = false
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    },
    // 从后台获取下拉框中所有机场信息
    getAllAirportFor () {
      let para = {
        header: JSON.stringify({
          beanId: 'airportService_v1',
          token: sessionStorage.getItem('token')
        }),
        body: JSON.stringify({})
      }
      apiBus.getAllAirport(para).then(res => {
        if (res.data.body.result === 1000) {
          // figureThree
          this.airportNameList = res.data.body.content.list
          for (let i = 0; i < this.airportNameList.length; i++) {
            this.airportNameList[i].label = this.airportNameList[i].figureThree + ' ' + this.airportNameList[i].airportName
          }
        } else {
          this.$message.error(res.data.body.resultDesp)
        }
      })
      .catch(error => {
        this.$message.error(error)
      })
    }
  },
  mounted () {
    this.tableWidth = document.body.scrollWidth - 259 - 20
  }
}
</script>